//
//  HomeViewController.swift
//  worldexchange
//
//  Created by xionghao on 2019/1/8.
//  Copyright © 2019 xionghao. All rights reserved.
//

import UIKit
import QMUIKit
import SnapKit
import MJRefresh
import RxSwift



class HomeViewController: QMUICommonViewController,UICollectionViewDelegate,UICollectionViewDataSource,HomeHeaderViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return moneyItems.count + 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if indexPath.row == moneyItems.count {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "addCell", for: indexPath) as! AddGridItemViewCell
            return cell
        } else {
            let cell =  collectionView.dequeueReusableCell(withReuseIdentifier: "exchangeCell", for: indexPath) as! ExcahngeGridViewCell
            let moneyItem = moneyItems[indexPath.row]
            let rate = moneyItem.rates[0]
            cell.buyValue.text = rate.buying
            cell.sellValue.text = rate.selling
            cell.dmValueLabel.text = rate.link
            cell.currencyLabel.text = moneyItem.ex_title
            cell.iconView.kf.setImage(with: URL(string: IMAGE_HOST + moneyItem.image))
            return cell
        }
       
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.row == moneyItems.count {
            showChangeFav()
        }else {
            let money = moneyItems[indexPath.row]
            if !isLogin {
                Utils.pushLogin()
            }else {
                
                let item = money.rates[0]
                let apVc = SubmitOrderViewController()
                item.money = money
                apVc.rate = item
                self.navigationController?.pushViewController(apVc, animated: true)
            }
        }
        
    }

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "headerView", for: indexPath)
        self.headerView = headerView as? HomeHeaderView
        self.headerView?.delegate = self
        self.refreshView()
        return headerView
    }
    
    func onHeaderViewActionClick(type: Int) {
        if type == 1 {
            let tabvc = self.navigationController?.tabBarController as? AppTabBarViewController
            tabvc?.showChangeShop()
        }
    }
    
    
    
    
    var headerView:HomeHeaderView?
    
    
    var banners = [String]()
    var moneyItems = [MoneyItem]()
    
    var selectedMoney = [String]()
    
    @IBOutlet weak var collectionView: UICollectionView!
    
    
  
    
   
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.refreshView()
    }
    
    func showChangeFav() {
        let contentVc = ChangeFavCurrencyViewController()
        contentVc.moneys = selectedMoney
        let modalVc = QMUIModalPresentationViewController()
        modalVc.contentViewController = contentVc
        modalVc.animationStyle = .slide
        contentVc.cancelBlock = {
            modalVc.dismiss(animated: true, completion: {
                self.setupMoneyItems()
                self.collectionView.reloadData()
            })
            
        }
        
        self.present(modalVc, animated: true)
    }
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //        self.title = LanguageHelper.getString(key: "CFBundleDisplayName")
        self.setupHeaderView()
        self.setupView()
         self.loadHtmlData()
        self.showEmptyViewWithLoading()
        self.emptyView.backgroundColor = UIColor.white
//        self.emptyView.textLabel.text = "正在加载中"
        self.loadData()
        NotificationCenter.default.addObserver(self, selector: #selector(receiveShopChange), name: NSNotification.Name.init(rawValue: changeShopNoticeName), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(receiveCurrencyChange), name: NSNotification.Name.init(rawValue: changeCurrencyNoticeName), object: nil)
    }
    
    
    func loadBanners() {
     
            provider.rx.request(WE.banner()).mapJSON().subscribe(onSuccess: { (result) in
                
                if let banners = result as? [String] {
                    self.banners.removeAll()
                    self.banners.append(contentsOf: banners)
                    self.refreshView()
                }
                
                
            }) { (error) in
                print(error)
            }
        
    }
    
    
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc func receiveShopChange() {
         self.loadRates()
    }
    
    @objc func receiveCurrencyChange(){
        self.loadRates()
    }
    
    
    func setupHeaderView() {
        
        let topLogoView =  TopLogoView.loadView()
        topLogoView.titleLabel.text = LanguageHelper.getString(key: "CFBundleDisplayName")
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: topLogoView)
        let telBtn = UIBarButtonItem.qmui_item(with: #imageLiteral(resourceName: "icon_tel"), target: self, action: #selector(telClick))
        let convertBtn = UIBarButtonItem.qmui_item(with: #imageLiteral(resourceName: "icon_covert"), target: self, action: #selector(convertClick))

        self.navigationItem.rightBarButtonItems = [telBtn,convertBtn]
        
    }
    
    @objc func convertClick(){
         let tabVc =  self.navigationController?.tabBarController as? AppTabBarViewController
        tabVc?.showConvert()
    }
    
    @objc func telClick(){
        let tabVc =  self.navigationController?.tabBarController as? AppTabBarViewController
        tabVc?.telClick()
    }
    
    
    func loadData() {
     
         provider.rx.request(WE.shop()).filterSuccessfulStatusCodes()
        .mapString()
            .subscribe(onSuccess: { (result) in
                if let shops = [ShopItem].deserialize(from: result) as? [ShopItem] {
                    if currentShop == nil {
                        currentShop = shops[0]
                    }
                    appShopItems.removeAll()
                    appShopItems.append(contentsOf: shops)
                    self.loadRates()
                }
                
            }) { (_) in
                self.showEmptyView(withText: "network error", detailText: "", buttonTitle: nil, buttonAction: nil)
        }
    }
    
    
    func setupMoneyItems() {
        self.moneyItems.removeAll()
        if var fav = UserDefaults.standard.dictionary(forKey: "favMoney") {
            if let values = fav["\(currentShop!.id)"] as? [String] {
                if values.count > 0 {
                    values.forEach { (key) in
                        appMoneyItems.forEach({ (item) in
                            if item.ex_title == key {
                                self.moneyItems.append(item)
                            }
                        })
                    }
                    selectedMoney = values
                }else {
                    let lastIndex = appMoneyItems.count > 5 ? 4 : appMoneyItems.count - 1
                    let subItems = appMoneyItems[0...lastIndex]
                    self.moneyItems.append(contentsOf: subItems)
                    let selected =  self.moneyItems.map { (item) -> String in
                        return item.ex_title
                    }
                    if selected.count > 0 {
                        fav["\(currentShop!.id)"] = selected
                        UserDefaults.standard.set(fav,forKey: "favMoney")
                        selectedMoney = selected
                    }
                    
                }
                
            }
        } else {
            let lastIndex = appMoneyItems.count > 5 ? 4 : appMoneyItems.count - 1
            let subItems = appMoneyItems[0...lastIndex]
            self.moneyItems.append(contentsOf: subItems)
            let selected =  self.moneyItems.map { (item) -> String in
                return item.ex_title
            }
            if selected.count > 0 {
               let fav =   ["\(currentShop!.id)":selected]
               UserDefaults.standard.set(fav,forKey: "favMoney")
                selectedMoney = selected
            }
        }
    }
    
    
    func loadRates() {
        self.showEmptyViewWithLoading()
        let contact_id = currentShop!.id
        let benchmark_id = defaultCurrency == "THB" ? 2 : 3
        provider.rx.request(WE.rate(contact_id: contact_id, benchmark_id: benchmark_id)).filterSuccessfulStatusCodes().mapString().subscribe(onSuccess: { (result) in
            if let item = RateResultItem.deserialize(from: result) {
                appMoneyItems.removeAll()
                appMoneyItems.append(contentsOf: item.rates)
               
                let serverTimeZone = TimeZone(identifier: "Asia/Shanghai")
                let systemTimeZone = TimeZone.current
                let formater = DateFormatter()
                formater.dateFormat = "yyyy-MM-dd HH:mm:ss"
                formater.timeZone = serverTimeZone
                let date = formater.date(from: item.last_updated)
                
                let formater2 = DateFormatter()
                formater2.dateFormat = "yyyy-MM-dd HH:mm:ss"
                formater2.timeZone = systemTimeZone
                
                let timeString =  formater2.string(from: date!)
                
                 lastUpdateTime = timeString
                self.moneyItems.removeAll()
                if appMoneyItems.count > 0 {
                   self.setupMoneyItems()
                }
               
                self.hideEmptyView()
                self.collectionView.mj_header.endRefreshing()
//                self.collectionView.refreshControl?.endRefreshing()
                self.collectionView.reloadData()
                self.loadBanners()
                 self.refreshView()
                NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: appMoneyLoadEndNoticeName), object: nil)
//                self.collectionView.mj_header.endRefreshing()
            }
            
        }) { (_) in
            self.showEmptyView(withText: "network error", detailText: "", buttonTitle: nil, buttonAction: nil)
        }
    }
    
    func refreshView()  {
       
        self.headerView?.lastUpdateTimeLabel.text = lastUpdateTime
        self.headerView?.shopNameLabel.text = currentShop?.title
        self.headerView?.bannerItems = banners
    }
    
    
    func loadHtmlData() {
        provider.rx.request(WE.about()).filterSuccessfulStatusCodes().mapString().subscribe(onSuccess: { (result) in
            if let item = ArticleItem.deserialize(from: result) {
                aboutItem = item
            }
        }) { (_) in
            
        }
        provider.rx.request(WE.tance()).filterSuccessfulStatusCodes().mapString().subscribe(onSuccess: { (result) in
            if let tance = ArticleItem.deserialize(from: result) {
                processItem = tance
            }
        }) { (_) in
            
        }
    }
    
    
    func setupData(moneyItem: MoneyItem?){
//        self.tableView.mj_header.endRefreshing()
        refreshData(moneyItem: moneyItem)
        
    }
    
    func refreshData(moneyItem:MoneyItem?) {
        var current:MoneyItem? = moneyItem
    }
    
    
    func setupView() {
        let nib = UINib(nibName: "ExcahngeGridViewCell", bundle: nil)
        let addNib = UINib(nibName: "AddGridItemViewCell", bundle: nil)
        let headerNib = UINib(nibName: "HomeHeaderView", bundle: nil)
        let layout = UICollectionViewFlowLayout()
        let screenWidth = UIScreen.main.bounds.width
        layout.headerReferenceSize = CGSize(width: screenWidth, height: 258)
        layout.itemSize = CGSize(width: (screenWidth - 36) / 2, height: 240)
        layout.minimumLineSpacing = 16
        layout.minimumInteritemSpacing = 12
        layout.sectionInset = UIEdgeInsets(top: 16, left: 12, bottom: 16, right: 12)
        
        self.collectionView.collectionViewLayout = layout
//        self.collectionView.backgroundColor = UIColor.qmui_color(withHexString: "#f3f3f3")
        
        self.collectionView.register(headerNib, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "headerView")
        self.collectionView.register(nib, forCellWithReuseIdentifier: "exchangeCell")
        self.collectionView.register(addNib, forCellWithReuseIdentifier: "addCell")
       
        
        
        
//        self.collectionView.refreshControl = UIRefreshControl()
        
//        let refresh = UIRefreshControl()
//        refresh.addTarget(self, action: #selector(refreshLoad), for: .valueChanged)
        
        let header = MJRefreshNormalHeader {
              self.loadData()
        }
        header?.lastUpdatedTimeLabel.isHidden = true
        header?.stateLabel.isHidden = true
        
        self.collectionView.mj_header = header
    }
    
//    @objc func refreshLoad()  {
//        self.loadData()
//    }
    

    
    func changeRate() {
        
    }
    
    
    func addPageControl() {
       
    }
    
   
    
    
   
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destination.
     // Pass the selected object to the new view controller.
     }
     */
    
}

